package com.utils.osu;


import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ApiUtil {

    private static Logger logger = LoggerFactory.getLogger(ApiUtil.class);

    public static String loopSend(String url) {
        String str = null;
        String data;
        int count = 5;
        while (count > 0) {
            try {
                Thread.sleep(500);
                logger.info("osu api --> " + url);
                data = HttpKit.get(url);
                logger.info("osu api result --> " + data);
                if (StrKit.notBlank(data)) {
                    str = data;
                    //获取成功 结束循环
                    break;
                } else {
                    count--;
                }
            } catch (Exception e) {
                count--;
            }
        }
        return str;
    }

    public static String getOsuApiStr(String username, int mode) {
        username = username.trim();
        username = username.replaceAll(" ", "%20");
        username = username.replaceAll("_", "%20");
        String url = "https://osu.ppy.sh/api/get_user?k=cda7da667c3c0d6b36e1ef1e7c1941e28e984310&m=" + mode + "&u=" + username;
        return loopSend(url);
    }

    public static String getRecentApi(String username, int mode) {
        username = username.trim();
        username = username.replaceAll(" ", "%20");
        username = username.replaceAll("_", "%20");
        String url = "https://osu.ppy.sh/api/get_user_recent?k=cda7da667c3c0d6b36e1ef1e7c1941e28e984310&limit=1&m=" + mode + "&u=" + username;
        return loopSend(url);
    }

    public static String getScoreApi(String username, int mode, String bid) {
        username = username.trim();
        username = username.replaceAll(" ", "%20");
        username = username.replaceAll("_", "%20");
        String url = "https://osu.ppy.sh/api/get_scores?k=cda7da667c3c0d6b36e1ef1e7c1941e28e984310&b=" + bid + "&m=" + mode + "&u=" + username;
        return loopSend(url);
    }

    public static String getScoreWithMod(int mods, int mode, String bid) {
        String url = "https://osu.ppy.sh/api/get_scores?k=cda7da667c3c0d6b36e1ef1e7c1941e28e984310&b=" + bid + "&m=" + mode + "&mods=" + mods;
        return loopSend(url);
    }

    public static String getBpApi(String username, int mode, int limit) {
        username = username.trim();
        username = username.replaceAll(" ", "%20");
        username = username.replaceAll("_", "%20");
        String url = "https://osu.ppy.sh/api/get_user_best?k=cda7da667c3c0d6b36e1ef1e7c1941e28e984310&limit=" + limit + "&m=" + mode + "&u=" + username;
        return loopSend(url);
    }


}
